package difficult.t124.maxPathSum;


import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/
 * 给你一个二叉树的根节点 root ，返回其 最大路径和
 *
 * 想法：
 * 当前节点的最大值为：max(root.val, root.val + root.left.val, root.val + root.right.val, root.val + root.left.val + root.right.val)
 * 可以为父节点提供的最大贡献：max(root.val, root.val + root.left.val, root.val + root.right.val)
 *
 * 执行用时：2 ms, 在所有 Java 提交中击败了48.37%的用户
 * 内存消耗：42 MB, 在所有 Java 提交中击败了34.52%的用户
 *
 * @Author luxiaoxiao
 * @Date 2022/1/10
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        int maxPath = solution.maxPathSum(root);
        System.out.println(maxPath);
    }

    /**
     * 计算最大路径
     *
     * @Author luxiaoxiao
     * @Date 2022/1/10
     */
    public int maxPathSum(TreeNode root) {
        Integer left = null;
        Integer right = null;
        if (root.left != null) {
            left = maxPathSum(root.left);
        }
        if (root.right != null) {
            right = maxPathSum(root.right);
        }
        int maxPath = maxPath(root);
        if (left != null && left > maxPath) {
            maxPath = left;
        }
        if (right != null && right > maxPath) {
            maxPath = right;
        }
        root.val = maxContribution(root);
        return maxPath;
    }


    /**
     * 以当前节点为顶点时的最大值
     *
     * @Author luxiaoxiao
     * @Date 2022/1/10
     */
    private int maxPath(TreeNode root) {
        int val = root.val;
        if (root.left != null && root.left.val > 0) {
            val += root.left.val;
        }
        if (root.right != null && root.right.val > 0) {
            val += root.right.val;
        }
        return val;
    }

    /**
     * 当前节点可以为父节点提供的最大贡献
     *
     * @Author luxiaoxiao
     * @Date 2022/1/10
     */
    private int maxContribution(TreeNode root) {
        int val = root.val;
        int max = Math.max(root.left != null ? root.left.val : 0, root.right != null ? root.right.val : 0);
        if (max > 0) {
            val += max;
        }
        return val;
    }

}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
